import React, { useEffect, useState } from "react";
import Taro, { useDidShow } from "@tarojs/taro";
import { View, Text, Input, Form, Button, Image } from "@tarojs/components";
import { getToken, removeToken } from "@/src/service";

import navWithAuth from "@/common/utils/navWithAuth";
import waitOpenToast from "@/common/utils/waitOpenToast";

import rightIcon from "@/images/icon_right.jpg";
import orderIcon from "@/images/order_icon.png";
import contractIcon from "@/images/contract_icon.png";

import myCollectIcon from "@/images/my_collect_icon.png";
import addressIcon from "@/images/address_icon.png";
import vipIcon from "@/images/vip_icon.png";
import personIcon from "@/images/person_icon.png";
import zanIcon from "@/images/zan_icon.png";
import messageIcon from "@/images//message_icon.png";
import * as noticeApi from "../notice/api";

import * as api from "./api";
import "./index.scss";

enum genderMap {
  man = 1,
  woman = 2,
}
const Index: React.FC<{}> = () => {
  const [customerInfo, setCustomerInfo] = useState<any>({});
  const [token, setToken] = useState<any>({});
  const [count, setCount] = useState<number>(0);

  useDidShow(() => {
    if (getToken().access_token) {
      setToken(getToken());
      getUserInfo();
      getUnReadCount()
    }
  });

  const getUserInfo = async () => {
    try {
      const { result, status } = await api.customer_myself_get({});
      if (status === "ok") {
        // Taro.setStorageSync("customer_info", result.customer_info);
        setCustomerInfo(result.customer_info);
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      Taro.hideLoading();
    }
  };
  const getUnReadCount = async () => {
    try {
      const { result, status } = await noticeApi.message_unreadcount({});
      if (status === "ok") {
        setCount(result.unread_count);
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
    }
  };
  const goLogin = () => {
    Taro.navigateTo({
      url: `/pages/loginGuide/index`,
    });
  };

  const logOut = () => {
    Taro.showActionSheet({
      itemList: ["您确定退出登录吗？"],
      itemColor: "#ff0000",
      success: async (res) => {
        console.log("res--->>", res);
        try {
          Taro.showLoading();
          const { result, status } = await api.customer_account_unbind({});
          Taro.hideLoading();
          if (status === "ok") {
            Taro.removeStorageSync("customer_info");
            removeToken();
            setCustomerInfo({});
            setToken({});
          }
        } catch (err) {
          console.log("err--------->>>", err);
        } finally {
          Taro.hideLoading();
        }
      },
      fail(err) {
        console.log("err------>>", err);
      },
    });
  };

  const onGetUserInfo = async (e) => {
    const { detail } = e;
    console.log("e----->>", detail);
    const { userInfo } = detail;
    if (detail.errMsg === "getUserInfo:ok") {
      const { _, status } = await api.customer_myself_update({
        myself_info: JSON.stringify({
          nick: userInfo.nickName, //char # 昵称 (选填)
          head_url: userInfo.avatarUrl, //char # 头像 (选填)
          gender: genderMap[userInfo.gender], //char # 性别 (选填)
        }),
      });

      if (status === "ok") {
        getUserInfo();
      }
    }
  };

  const goNotice = () => {
    console.log('goNotice---->>')
    Taro.navigateTo({
      url: `/pages/notice/index`,
    });
  };

  return (
    <View className="mine-page">
      {token.access_token && (
        <View className="message" onClick={goNotice}>
          <Image src={messageIcon} />
          {count ? <View className="status">{count}</View> : null}
        </View>
      )}
      {token.access_token ? (
        <Button
          className="user-info"
          openType="getUserInfo"
          onGetUserInfo={onGetUserInfo}
        >
          <Image
            className="header-img"
            src={customerInfo.head_url || personIcon}
          />
          <View className="text">{customerInfo.nick}</View>
        </Button>
      ) : (
        <View className="user-info" onClick={goLogin}>
          <Image className="header-img" src={personIcon} />
          <View className="text">未登录</View>
          <Image className="arrow" src={rightIcon} />
        </View>
      )}

      <View className="cell-area">
        <View className="sub-title">我的课程</View>
        <View className="cell-wrapepr">
          <View
            className="cell-item"
            onClick={() => {
              navWithAuth("/pages/orderList/index");
            }}
          >
            <Image className="icon" mode="heightFix" src={orderIcon} />
            <View className="text">我的订单</View>
          </View>
          <View
            className="cell-item"
            onClick={() => {
              navWithAuth("/pages/contractList/index");
            }}
          >
            <Image className="icon" mode="heightFix" src={contractIcon} />
            <View className="text">我的合同</View>
          </View>
          <View
            className="cell-item"
            onClick={() => {
              navWithAuth("/pages/collectList/index");
            }}
          >
            <Image className="icon" mode="heightFix" src={myCollectIcon} />
            <View className="text">我的收藏</View>
          </View>
        </View>
      </View>

      <View className="list-wrapper">
        <View className="list-item" onClick={waitOpenToast}>
          <Image className="icon" src={zanIcon} mode="heightFix" />
          <View className="text">意见反馈</View>
          <Image className="arrow" src={rightIcon} />
        </View>

        <View className="list-item" onClick={waitOpenToast}>
          <Image className="icon" src={vipIcon} mode="heightFix" />
          <View className="text">关于我们</View>
          <Image className="arrow" src={rightIcon} />
        </View>
      </View>

      {getToken().access_token && (
        <View className="logout" onClick={logOut}>
          退出登录
        </View>
      )}
    </View>
  );
};

export default Index;
